package com.showmaker.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.showmaker.bean.Setmeal;
import com.showmaker.constant.RedisConstant;
import com.showmaker.entity.PageResult;
import com.showmaker.entity.QueryPageBean;
import com.showmaker.mapper.SetmealMapper;
import com.showmaker.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Transactional
@DubboService(interfaceClass = SetmealService.class, version = "1.0")
public class SetmealServiceImpl implements SetmealService {

    @Value("${ftl.path}")
    private String ftlOutputPath;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void add(Integer[] checkgroupIds, Setmeal setmeal) {
        // 将套餐的具体信息添加到 t_setmeal 表中
        setmealMapper.insert(setmeal);

        // 将与套餐关联的检查组的信息添加到 t_setmeal_checkgroup 表中
        HashMap<String, Object> map = new HashMap<>();
        map.put("setmealId", setmeal.getId());
        map.put("checkgroupIds", checkgroupIds);
        setmealMapper.insertConnections(map);

        // 当套餐成功上传后，将图片的地址添加 redis 中
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        // 新增套餐后，生成套餐的静态页面
        // 同样的，每当套餐修改、删除时，也需要生成静态页面
        //generateMobileStaticHtml();
    }

    // 生成静态页面
    private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = this.selectAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    // 生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
    }

    // 生成套餐详情静态页面(多个)
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("setmeal", this.getSetmeal(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                            "setmeal_detail_" + setmeal.getId() + ".html",
                            dataMap);
        }
    }

    // 生成静态的 html 模版
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            // 加载模版文件
            Template template = configuration.getTemplate(templateName);
            // 生成数据
            File file = new File(ftlOutputPath + "\\" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            // 输出文件
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageResult page(QueryPageBean queryPageBean) {
        // 获取相关的查询条件
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        // 如果需要按照条件进行，那么返回的结果就是从第1页开始展示的
        if (queryString != null) {
            currentPage = 1;
        }

        // 使用分页助手进行分页查询
        PageHelper.startPage(currentPage, pageSize);

        // 调用 mapper 进行查询
        Page<Setmeal> page = setmealMapper.page(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public List<Setmeal> selectAll() {
        return setmealMapper.selectAll();
    }

    @Override
    public Setmeal getSetmeal(Integer id) {
        return setmealMapper.getSetmeal(id);
    }

    @Override
    public List<Map<String, Object>> getSetmealCount() {
        return setmealMapper.getSetmealCount();
    }
}
